package wx.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import config.Interceptor.PassToken;
import details.controller.Userdetailscontroller;
import details.entity.Wxuserdetails;
import details.mapper.WxuserdetailsMapper;
import details.service.impl.Userdetailsserviceimpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import utils.CommonRetumType;
import utils.error.BusinessException;
import utils.error.EmBusinessError;
import wx.entity.Wxuser;
import wx.mapper.WxuserMapper;
import wx.utils.WechatUtil;

import javax.annotation.Resource;
import java.util.*;
@RestController
public class Wxuserlogin {
    @Resource
    private WxuserMapper wxUserMapper;

    @Autowired
    private Userdetailsserviceimpl userdetailsserviceimpl;

    /**
     * 微信用户登录详情
     */
    @PostMapping("wx/login")
    @PassToken
    public CommonRetumType user_login(@RequestParam(value = "code", required = false) String code,
                                      @RequestParam(value = "rawData", required = false) String rawData,
                                      @RequestParam(value = "signature", required = false) String signature,
                                      @RequestParam(value = "encrypteData", required = false) String encrypteData,
                                      @RequestParam(value = "iv", required = false) String iv,
                                      @RequestParam(value = "nickName",required = false) String nickName,
                                      @RequestParam(value = "avatarUrl",required = false) String avatarUrl) {
        // 用户非敏感信息：rawData
        // 签名：signature
        JSONObject rawDataJson = JSON.parseObject(rawData);
        // 1.接收小程序发送的code
        // 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
        JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(code);
        // 3.接收微信接口服务 获取返回的参数
        String openid = SessionKeyOpenId.getString("openid");
        String sessionKey = SessionKeyOpenId.getString("session_key");
        // 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
        String signature2 = DigestUtils.sha1Hex(rawData + sessionKey);
        // 5.根据返回的User实体类，判断用户是否是新用户，是的话，将用户信息存到数据库；不是的话，更新最新登录时间
        Wxuser user = wxUserMapper.selectByPrimaryKey(openid);
        // uuid生成唯一key，用于维护微信小程序用户与服务端的会话
        String skey = UUID.randomUUID().toString();


        if (user == null) {
            // 用户信息入库
//            String nickName = rawDataJson.getString("nickName");
//            String avatarUrl = rawDataJson.getString("avatarUrl");

            String gender = rawDataJson.getString("gender");
            String city = rawDataJson.getString("city");
            String country = rawDataJson.getString("country");
            String province = rawDataJson.getString("province");

            Wxuser wxUser= new Wxuser();
            wxUser.setOpenId(openid);
            wxUser.setSkey(skey);
            wxUser.setCreateTime(new Date());
            wxUser.setLastVisitTime(new Date());
            wxUser.setSessionKey(sessionKey);
            wxUser.setCity(city);
            wxUser.setProvince(province);
            wxUser.setCountry(country);
            wxUser.setAvatarUrl(avatarUrl);
            wxUser.setGender((byte)Integer.parseInt(gender));
            wxUser.setNickName(nickName);

            if (avatarUrl == null)
            {

                return CommonRetumType.create(0,"微信头像url不能为空");
            }else {
                System.out.println("avatarUrl不为空");
                System.out.println(wxUser.getOpenId());

                Userdetailscontroller userdetailscontroller = new Userdetailscontroller();
                Wxuserdetails wxuserdetails = new Wxuserdetails();
                wxuserdetails.setOpenId(wxUser.getOpenId());
                wxuserdetails.setUsername(nickName);
//                添加到用户详情
                userdetailsserviceimpl.insertSelective(wxuserdetails);
                wxUserMapper.insertSelective(wxUser);
                HashMap<String,String> hashMap1 = new HashMap<>();
                hashMap1.put("openid",wxUser.getOpenId());
                hashMap1.put("sessionKey",wxUser.getSessionKey());
                hashMap1.put("skey",wxUser.getSkey());
                hashMap1.put("avatarUrl",avatarUrl);
                hashMap1.put("nickName", nickName);
                return CommonRetumType.create(hashMap1,"微信用户添加成功");
            }


        } else {
            // 已存在，更新用户登录时间
            Wxuser wxUser = new Wxuser();
            wxUser.setLastVisitTime(new Date());
            // 重新设置会话skey
            wxUser.setSkey(skey);
            wxUserMapper.updateByPrimaryKeySelective(user);
            HashMap<String,String> hashMap = new HashMap<>();
            hashMap.put("openid",openid);
            hashMap.put("sessionKey",sessionKey);
            hashMap.put("skey",skey);
            hashMap.put("avatarUrl",user.getAvatarUrl());
            hashMap.put("nickName", user.getNickName());
            return CommonRetumType.create(hashMap,"微信用户请求成功");
        }
    }

    @GetMapping("wx/read")
    @PassToken
    public CommonRetumType read(@RequestParam("openId") String openid)
    {
        Wxuserdetails wxuserdetails = userdetailsserviceimpl.selectOpenid(openid);
        Wxuser wxuser = wxUserMapper.selectByPrimaryKey(openid);
        wxuserdetails.setAvatarurl(wxuser.getAvatarUrl());
        return CommonRetumType.create(wxuserdetails,"获取成功");
    }
}
